package controller

import (
	"fmt"
	"net/http"
	"strconv"
	"study_abroad_system_back_end/common/StatusCode"
	"study_abroad_system_back_end/dao"
	"study_abroad_system_back_end/models"
	"study_abroad_system_back_end/response"
	"study_abroad_system_back_end/serializer"
	"github.com/gin-gonic/gin"
)

func UpdateInfo(ctx *gin.Context) {
	code := StatusCode.SUCCESS

	se := ctx.PostForm("sex")
	var sex int
	if se == "男" {
		sex = 1
	} else {
		sex = 0
	}

	qq := ctx.PostForm("qq")
	email := ctx.PostForm("email")
	avatar := ctx.PostForm("avatar")
	gpa, _ := strconv.ParseFloat(ctx.PostForm("gpa"), 2)
	gpa32 := float32(gpa)
	sat, _ := strconv.Atoi(ctx.PostForm("sat"))
	ielts, _ := strconv.ParseFloat(ctx.PostForm("ielts"), 2)
	ielts32 := float32(ielts)
	toefl, _ := strconv.ParseFloat(ctx.PostForm("toefl"), 2)
	toefl32 := float32(toefl)

	s := ctx.Param("id")
	id, _ := strconv.Atoi(s)

	DB := dao.GetDB()
	var user models.User
	fmt.Println(id)
	DB.First(&user, id)
	DB.Table("users").Where("id=?", id).Updates(models.User{Sex: sex, QQ: qq, Email: email, Avatar: avatar,
	GPA: gpa32, SAT: sat, IELTS: ielts32, TOEFL: toefl32})

	response.Response(ctx, http.StatusOK, code, gin.H{"message": "更新成功！"}, StatusCode.GetMsg(code))
	
}

func QueryInfo(ctx *gin.Context) {
	code := StatusCode.SUCCESS

	s := ctx.Param("id")
	id, _ := strconv.Atoi(s)

	var user models.User
	
	DB := dao.GetDB()
	DB.First(&user, id)

	response.Response(ctx, http.StatusOK, code, gin.H{
		"user": gin.H{
			"id": user.ID,
			"telephone": user.Telephone,
			"sex" : user.Sex,
			"qq": user.QQ,
			"email": user.Email,
			"avatar": user.Avatar,
			"gpa": user.GPA,
			"sat": user.SAT,
			"ielts": user.IELTS,
			"toefl": user.TOEFL,
		},
	}, StatusCode.GetMsg(code))
}

func CollegeRecommend(ctx *gin.Context) {
	code := StatusCode.SUCCESS

	s := ctx.Param("id")
	id, _ := strconv.Atoi(s)

	var user models.User
	
	DB := dao.GetDB()
	DB.First(&user, id)

	var score float32
	score = 50 * (user.GPA / 5.0) + 30 * (float32(user.SAT) / 1600) + 10 * (user.IELTS / 9) + 10 * (user.TOEFL / 120)
	var max, min int
	switch {
	case 100>=score && score>90: max=100; min=90
	case 90>=score && score>80: max=90; min=80
	case 80>=score && score>70: max=80; min=70
	case 70>=score && score>60: max=70; min=60
	case 60>=score && score>50: max=60; min=50
	case 50>=score && score>40: max=50; min=40
	case 40>=score && score>30: max=40; min=30
	case 30>=score && score>20: max=30; min=20
	case 20>=score && score>10: max=20; min=10
	case 10>=score && score>0: max=10; min=0
	}
	
	var college []models.College
	DB.Table("colleges").Where("overall<=? AND overall>?", max, min).Find(&college)
	if len(college) <= 5{
		response.Response(ctx, http.StatusOK, code, gin.H{"collegeRecommend": serializer.BuildCollegesList(college)}, StatusCode.GetMsg(code))
	}else{
		response.Response(ctx, http.StatusOK, code, gin.H{"collegeRecommend": serializer.BuildCollegesList(college[:5])}, StatusCode.GetMsg(code))
	}
}
